#include <func.h>

#define LOGIN 0
#define REGISTER 1
//返回用户名
char *userClient(int sockFd)
{
    int type;
    char *userName = calloc(30, sizeof(char));
    printf("please choose a option:\n0: login\n1: register\n");

    while (1)
    {
        scanf("%d", &type);
        if (type == 0 || type == 1)
            break;
        puts("Please enter a correct option!");
    }
    puts("please enter user name:");
    scanf("%s", userName);

    //发送登录or注册信息及用户名
    int ret = send(sockFd, &type, sizeof(type), 0);
    ERROR_CHECK(ret, -1, "send sockFd in userClient");
    int datalen = strlen(userName);
    ret = send(sockFd, &datalen, sizeof(datalen), 0);
    ERROR_CHECK(ret, -1, "send username datalen in removeClient");
    ret = send(sockFd, userName, datalen, 0);
    ERROR_CHECK(ret, -1, "send  username dataInfor in removeClient");
    //接受错误标志
    int failFlag;
    recvn(sockFd, &failFlag, sizeof(failFlag));
    if (failFlag == 1)
    {
        printf("%s failed, %s %s exist!\n", type == LOGIN ? "login" : "register", userName, type == LOGIN ? "not" : "already");
        return NULL;
    }
    //接收盐值
    char salt[12];
    recvn(sockFd, salt, sizeof(salt));

    printf("please enter the password:\n");
    char userpsd[128] = {0};
    scanf("%s", userpsd);

    //生成并发送密文
    char *ciphertext = crypt(userpsd, salt);
    datalen = strlen(ciphertext);
    ret = send(sockFd, &datalen, sizeof(datalen), 0);
    ERROR_CHECK(ret, -1, "send sockFd in userClient");
    ret = send(sockFd, ciphertext, datalen, 0);
    ERROR_CHECK(ret, -1, "send ciphertext in userClient");

    //接受反馈信息
    recvn(sockFd, &failFlag, sizeof(failFlag));
    if (failFlag == 1 && type == LOGIN)
    {
        puts("login failed!");
        return NULL;
    }
    puts("login in success!");

    return userName;
}